package com.bookcode.controller;
import com.bookcode.dao.UserRepository;
import com.bookcode.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@Controller
public class UserPictureController {
    @Autowired
    UserRepository userRepository;
    @GetMapping(value="/zhuce")
    public String zhuce(){
        return "zhuce";
    }
    @PostMapping(value="/zhuce")
    public String tijiao(@RequestParam(value="name") String name,
                         @RequestParam(value="password") String password,
                         @RequestParam(value="file")MultipartFile file,
                         Model model) {
        User user = new User();
        user.setUsername(name);
        user.setPassword(password);
        if (!file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new
                        File("D:\\ch83\\src\\main\\webapp\\"+name+".jpg")));//保存图片到目录下
                out.write(file.getBytes());
                out.flush();
                out.close();
                String  filename="D:\\ch83\\src\\main\\webapp\\"+name+".jpg";
                user.setTupian(filename);
                userRepository.save(user);//增加用户
            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            model.addAttribute(user);
            return "permanager";
        }
        else {
            return "上传失败，因为文件是空的.";
        }
    }
}
